package com.example.servicedemo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.servicedemo.MainActivity;

public class RandomService extends Service {
    private Thread workThread;
    private Runnable backgroundWork = new Runnable() {
        @Override
        public void run() {
            try {
                while(!Thread.interrupted()){
                    //过程代码
                    double random = Math.random();
                    MainActivity.UpdateGUI(random);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
//        String msg = "随机数:" + Math.random();
//        Toast.makeText(this,  msg, Toast.LENGTH_SHORT).show();
        //启动线程
        if(!workThread.isAlive()){
            workThread.start();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
        //创建线程
        workThread = new Thread(null, backgroundWork,"WorkThread");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
        workThread.interrupt();
    }
}
